package networks.protocol;

import java.util.Timer;
import java.util.TimerTask;

public class HeartbeatService {
    private int _interval;
    private int _timeout;
    private Timer _timer;
    private long _lastTime;
    private Protocol _protocol;

    public HeartbeatService(float heartbeatTime, Protocol protocol) {
        _interval = (int) (heartbeatTime * 1000);
        _protocol = protocol;
    }

    public void Start() {
        if (_interval < 1000) {
            return;
        }

        // start hearbeat
        _timer = new Timer();
        _timer.schedule(new TimerTask() {
            public void run() {
                sendHeartBeat();
            }
        }, _interval, _interval);

        // Set timeout
        _timeout = 0;
        _lastTime = System.currentTimeMillis();
    }

    public void ResetTimeout() {
        _timeout = 0;
        _lastTime = System.currentTimeMillis();
    }

    public void Stop() {
        if (_timer != null) {
            _timer.cancel();
        }
    }

    private void sendHeartBeat() {
        System.out.println("HeartBeat!");
        long span = System.currentTimeMillis() - _lastTime;
        _timeout = (int) span;

        // check timeout
        if (_timeout > _interval * 2 * 1000) {
            System.out.println("HeartBeat timeout!");
            _protocol.getClient().Disconnect();
            // stop();
            return;
        }

        // Send heart beat
        _protocol.Send(PackageType.PKG_HEARTBEAT);
    }
}
